
import React, { useState, useEffect } from 'react';
import { Card, Form, Input, Button, Select, DatePicker, Upload, Row, Col, message } from 'antd';
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons';
import { history, useParams } from '@umijs/max';
import { getBookDetail, updateBook } from '@/services/bookAPi';
import { getCategories } from '@/services/categoryApi';
import type { BookItem } from '@/types/book';

const { Option } = Select;
const { RangePicker } = DatePicker;

const BookEdit: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [categories, setCategories] = useState<any[]>([]);
  const [uploadFileList, setUploadFileList] = useState<any[]>([]);

  // 获取图书详情
  const fetchBookDetail = async () => {
    if (!id) return;

    setLoading(true);
    try {
      const res = await getBookDetail(Number(id));
      form.setFieldsValue({
        ...res.data,
        publish_date: res.data.publish_date ? [new Date(res.data.publish_date)] : null,
      });

      if (res.data.cover_image) {
        setUploadFileList([{
          uid: '-1',
          name: 'cover_image',
          status: 'done',
          url: res.data.cover_image,
        }]);
      }
    } catch (error) {
      message.error('获取图书详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      const res = await getCategories();
      setCategories(res.data.results);
    } catch (error) {
      message.error('获取分类列表失败');
    }
  };

  useEffect(() => {
    fetchBookDetail();
    fetchCategories();
  }, [id]);

  // 处理文件上传
  const handleUpload = (info: any) => {
    if (info.file.status === 'done') {
      setUploadFileList([info.file]);
    } else if (info.file.status === 'error') {
      message.error('封面上传失败');
    } else {
      setUploadFileList([info.file]);
    }
  };

  // 提交表单
  const handleSubmit = async (values: any) => {
    if (!id) return;

    setLoading(true);
    try {
      const formData = new FormData();
      Object.keys(values).forEach(key => {
        if (values[key] !== undefined && values[key] !== null) {
          if (key === 'publish_date' && values[key] instanceof Array) {
            formData.append(key, values[key][0].toISOString().split('T')[0]);
          } else {
            formData.append(key, values[key]);
          }
        }
      });

      if (uploadFileList.length > 0 && uploadFileList[0].originFileObj) {
        formData.append('cover_image', uploadFileList[0].originFileObj);
      }

      await updateBook(Number(id), formData);
      message.success('更新成功');
      history.push('/books/list');
    } catch (error) {
      message.error('更新失败');
    } finally {
      setLoading(false);
    }
  };

  // 状态选项
  const statusOptions = [
    { value: 'available', label: '可借阅' },
    { value: 'borrowed', label: '已借出' },
    { value: 'reserved', label: '已预约' },
    { value: 'damaged', label: '损坏' },
    { value: 'lost', label: '丢失' },
  ];

  // 语言选项
  const languageOptions = [
    { value: '中文', label: '中文' },
    { value: '英文', label: '英文' },
    { value: '日文', label: '日文' },
    { value: '其他', label: '其他' },
  ];

  return (
    <div>
      <Card style={{ marginBottom: 16 }}>
        <Button 
          icon={<ArrowLeftOutlined />} 
          onClick={() => history.push('/books/list')}
        >
          返回列表
        </Button>
      </Card>

      <Card title="编辑图书">
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{
            language: '中文',
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="title"
                label="书名"
                rules={[{ required: true, message: '请输入书名' }]}
              >
                <Input placeholder="请输入书名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="author"
                label="作者"
                rules={[{ required: true, message: '请输入作者' }]}
              >
                <Input placeholder="请输入作者" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="isbn"
                label="ISBN"
                rules={[{ required: true, message: '请输入ISBN' }]}
              >
                <Input placeholder="请输入ISBN" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="publisher"
                label="出版社"
                rules={[{ required: true, message: '请输入出版社' }]}
              >
                <Input placeholder="请输入出版社" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="publish_date"
                label="出版日期"
                rules={[{ required: true, message: '请选择出版日期' }]}
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="category"
                label="分类"
                rules={[{ required: true, message: '请选择分类' }]}
              >
                <Select placeholder="请选择分类">
                  {categories.map(category => (
                    <Option key={category.id} value={category.id}>
                      {category.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select placeholder="请选择状态">
                  {statusOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="language"
                label="语言"
                rules={[{ required: true, message: '请选择语言' }]}
              >
                <Select placeholder="请选择语言">
                  {languageOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="page_count"
                label="页数"
                rules={[{ required: true, message: '请输入页数' }]}
              >
                <Input type="number" placeholder="请输入页数" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea rows={4} placeholder="请输入图书描述" />
          </Form.Item>

          <Form.Item
            name="cover_image"
            label="封面图片"
          >
            <Upload
              fileList={uploadFileList}
              onChange={handleUpload}
              maxCount={1}
              listType="picture-card"
            >
              {uploadFileList.length < 1 && (
                <div>
                  <div style={{ marginTop: 8 }}>上传封面</div>
                </div>
              )}
            </Upload>
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              icon={<SaveOutlined />}
              loading={loading}
            >
              保存修改
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default BookEdit;
